<?php
namespace Admin\Model;

use Think\Model\RelationModel;

class CategoryModel extends RelationModel
{

    protected $_validate = array(
        array('parent_id', 'require', '父栏目必须！'),
        array('name', 'require', '名称必须！'),
        array('name', '', '栏目名称已经存在！', 0, 'unique', 1), // 在新增的时候验证name字段是否唯一
        array('pinyin', 'require', '拼音必须！'),
        array('url', 'URL', '请填写URL地址！',2),
    );

    protected $_link = array(
        'children' => array(
            'mapping_type' => self::HAS_MANY,
            'class_name' => 'Category',
            'foreign_key' => 'parent_id',
            'mapping_order' => 'sort_order',
        )
    );

    public function reSort($array)
    {
        return $this->_reSort($array);
    }

    private function _reSort($array, $parent_id = 0, $level = 0)
    {
        static $data = array();
        foreach ($array as $k => $v) {
            if ($v['parent_id'] == $parent_id) {
                $v['level'] = $level;
                $data[] = $v;
                //unset($array[$k]);
                $this->_reSort($array, $v['id'], $level + 1);
            }
        }
        //echo "111";
        return $data;
    }

}